package com.farsunset.ichat.example.receiver;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.util.Log;

import com.farsunset.cim.client.android.CIMDataConfig;
import com.farsunset.cim.client.android.CIMEnventListenerReceiver;
import com.farsunset.cim.client.android.CIMListenerManager;
import com.farsunset.cim.client.android.CIMPushManager;
import com.farsunset.cim.nio.constant.CIMConstant;
import com.farsunset.cim.nio.model.ObjectConvertUtil;
import com.farsunset.cim.nio.model.ResponseFile;
import com.farsunset.cim.nio.mutual.Message;
import com.farsunset.cim.nio.mutual.ReplyBody;
import com.farsunset.cim.nio.mutual.SentBody;
import com.farsunset.cim.nio.util.MD5FileUtil;
import com.farsunset.ichat.example.R;
import com.farsunset.ichat.example.ui.LoginActivity;
import com.farsunset.ichat.example.ui.SystemMessageActivity;
 
/**
 *  消息入口，所有消息都会经过这里
 * @author 3979434
 *
 */
public final class CustomCIMMessageReceiver extends CIMEnventListenerReceiver {
 
	private NotificationManager notificationManager;
	
	//文件相关
	private static int byteRead;
	private volatile static long start = 0;
	public static RandomAccessFile randomAccessFile;
	//读取大小
	private final static int minReadBufferSize = 1024 * 20;
 
	
	
	//当收到消息时，会执行onMessageReceived，这里是消息第一入口
	@Override
	public void onMessageReceived(com.farsunset.cim.nio.mutual.Message message) {
		for (int index = 0 ;index<CIMListenerManager.getCIMListeners().size();index++) {
			
			Log.i(this.getClass().getSimpleName(), "########################"+ (CIMListenerManager.getCIMListeners().get(index).getClass().getName() + ".onMessageReceived################"));
			
			CIMListenerManager.getCIMListeners().get(index).onMessageReceived(message);
		}
		
		//以开头的为动作消息，无须显示,如被强行下线消息Constant.TYPE_999
		if(message.getType().startsWith("9"))
		{
			return ;
		}
		if(isInBackground(context))
		{
			showNotify(context,message);
		}
	}


	//当手机网络连接状态变化时，会执行onNetworkChanged 
	@Override
	public void onNetworkChanged(NetworkInfo info) {
		for (int index = 0 ;index<CIMListenerManager.getCIMListeners().size();index++) {
			CIMListenerManager.getCIMListeners().get(index).onNetworkChanged(info);
		}
	}

	//当收到sendbody的响应时，会执行onReplyReceived 
	@Override
	public void onReplyReceived(ReplyBody body) {
		for (int index = 0 ;index<CIMListenerManager.getCIMListeners().size();index++) {
			
			System.out.println("接收到的反馈数据为:"+body);
			
			//这里只能是
			if("client_trans_file".equals(body.getKey())){
				
				//在这里要进行将消息转换为类对象
				String fileData = body.getMessage();
				System.out.println("接收到的反馈数据为message:"+fileData);
				
				
				//执行客户端传递文件的写法
				
				
				//将data转换为对象
				ResponseFile response = (ResponseFile) ObjectConvertUtil.convertModle(fileData);
				
				System.out.println("转换为对象后的数据:"+response.toString());
				
				/*
				 * 转换为对象后的数据:ResponseFile [code=null, end=0, file_md5=6e397233eb4330492ce44268748cae74, file_url=null, progress=49, start=20480]
				 */
				String code = response.getCode();
				String end = response.getEnd();
				if ("1".equals(response.getEnd())) {
					//TODO 上传完成，客户端再次用于判别
//					randomAccessFile.close();
//					ctx.close();
					//当code =0000 end=1的时候表示上传成功并且完成
					if("0000".equals(code)){
						System.out.println("------表示上传成功并且完成---------");
					} else if("".equals("-3003")){
						System.out.println("------表示上传失败---------");
					}
					//当code = 0000 end =0 的时候表示断点续传，本次成功，后续还要传输
					
					//当code = -3003 那么表示失败
					
					
				} else if("0000".equals(code)){
					
					File file = CIMDataConfig.fileMap.get(response.getFile_md5());
					
					start = response.getStart();
					if (start != -1) {
						int a = 0;
						//已只读的方式读取此文件
						try {
							randomAccessFile = new RandomAccessFile(file,
									"r");
							randomAccessFile.seek(start);
							a = (int) (randomAccessFile.length() - start);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						//a=文件总长度-开始位置 = 剩余量
						//赋值为最小读取长度
						int sendLength = minReadBufferSize;
						//当剩余量小于最小长度
						if (a < minReadBufferSize) {
							sendLength = a;
						}
						byte[] bytes = new byte[sendLength];
						SentBody sent = new SentBody();
						sent.put("fileName", file.getName());
						
						String bytesStr = "";
						try {
							if ((byteRead = randomAccessFile.read(bytes)) != -1
									&& (randomAccessFile.length() - start) > 0) {
								bytesStr = com.farsunset.cim.nio.util.Base64Coder.encode(bytes);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						sent.put("bytes", bytesStr);
						sent.put("startPos", "0");
						sent.put("endPos", byteRead+"");
						
						String fileMd5 = "";
						try {
							fileMd5 = MD5FileUtil.getFileMD5String(file);
						} catch (Exception e1) {
							e1.printStackTrace();
						}
						
						sent.put("fileMd5", fileMd5);
						sent.put("fileSize", file.length()+"");
						sent.setKey(CIMConstant.RequestKey.CLIENT_TRANS_FILE);
						
						System.out.println("再次发送 的数据为:"+sent.toString());
						
						//TODO 这里可以需要处理下，采用的是登陆的  context
						CIMPushManager.sendRequest(LoginActivity.context, sent);
					}
				} else {
					//TODO ..上传失败
					System.out.println("上传失败....");
				}
				
			} else if("client_sendMsg".equals(body.getKey())) {
				//这里可以处理客户端主动发送消息后 服务器的反馈的结果 
				
			} else {
				CIMListenerManager.getCIMListeners().get(index).onReplyReceived(body);
			}
		}
	}
	 
	
	private void  showNotify(Context context , Message msg)
	{
				
		this.notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		String title  = "系统消息";
        
		Notification notification = new Notification(R.drawable.icon_notify,title,msg.getTimestamp());
		notification.defaults = Notification.DEFAULT_LIGHTS;
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		
		Intent notificationIntent = new Intent(context,SystemMessageActivity.class);
		PendingIntent contentIntent = PendingIntent.getActivity(context,1, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		notification.contentIntent = contentIntent;
		notification.setLatestEventInfo(context,title,  msg.getContent(),contentIntent);
		notificationManager.notify(R.drawable.icon_notify, notification);

	}


	public void onConnectionSucceed() {
		for (int index = 0 ;index<CIMListenerManager.getCIMListeners().size();index++) {
			CIMListenerManager.getCIMListeners().get(index).onConnectionSucceed();
		}
	}


	@Override
	public void onConnectionStatus(boolean arg0) {
		for (int index = 0 ;index<CIMListenerManager.getCIMListeners().size();index++) {
			CIMListenerManager.getCIMListeners().get(index).onConnectionStatus(arg0);
		}
	}
	@Override
	public void onConnectionClosed() {
		for (int index = 0 ;index<CIMListenerManager.getCIMListeners().size();index++) {
			CIMListenerManager.getCIMListeners().get(index).onConnectionClosed();
		}
	}
 
}
